
/**
 * 通过`meta.roles`判断是否与当前用户权限匹配
 * @param roles {Array}，用户角色，只有一个数组项则用于验证当前角色权限，若有多个数组项则是验证所有角色的综合权限
 * @param route {Object}，路由对象
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = [];

  routes.forEach(route => {
    const tmp = { ...route };
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  });

  return res
}

const permission = {
  state: {
    routes: [],
    addRoutes: []
  },
  mutations: {
    SET_ROUTES: (state, data) => {
      const { accessedRoutes, constantRoutes } = data;
      state.addRoutes = accessedRoutes;
      state.routes = constantRoutes.concat(accessedRoutes)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { roles, asyncRoutes, constantRoutes } = data;
        const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
        commit('SET_ROUTES', { accessedRoutes, constantRoutes });
        resolve(accessedRoutes)
      })
    }
  }
};

export default permission
